package com.xhwl.centiotdata.handler.account.impl;

import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.account.AccountFactory;
import com.xhwl.centiotdata.handler.account.AccountHandler;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IAccountCentService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.cent.IProjectCentService;
import com.xhwl.centiotdata.suppliersystem.aolai.GeneralAoLaiHandler;
import com.xhwl.common.dto.cent.sdata.AccountDTO;
import com.xhwl.common.dto.cent.sdata.PermissionGroupDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.enums.config.IndustryEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.pojo.cent.sdata.Role;
import com.xhwl.common.pojo.cent.sdata.personnel.StaffDTO;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import com.xhwl.common.query.cent.sdata.AccountQuery;
import com.xhwl.common.query.cent.sdata.RoleQuery;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.common.utils.function.MyStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangyiling
 * @description 奥莱主数据相互同步
 * @date 2022/9/27 15:32
 */
@Slf4j
@Service
public class AccountAoLaiHandler extends AccountHandler {
    @Resource
    private IDeviceCentService iDeviceCentService;

    @Resource
    private IAccountCentService accountCentService;

    @Resource
    private IProjectCentService projectCentService;

    private static final String GET_STAFF_URL = "/cent-data-core/staff/list";

    @Autowired
    private GeneralAoLaiHandler generalAoLaiHandler;

    @Override
    public String syncUserAuto(PedestrianIntegrationConfigDTO configDTO) {
        String userOpenId = "";
        try {
            Project project = projectCentService.findById(configDTO.getProjectId());
            if (project == null) {
                throw new DataException("项目信息不存在！");
            }
            // 新增住户人员信息
            List<DeviceProjSupplierCategory> deviceConfigList = iDeviceCentService.listProductAccess((short) 1, new ProductAccessQuery(configDTO.getProjectId(), CategoryEnum.DOOR.getId()));
            DeviceProjSupplierCategory deviceConfig = deviceConfigList.stream().filter(s->s.getProductId().equals(configDTO.getProductId())).findAny().orElse(null);
            if(deviceConfig != null){
                JSONObject properties = deviceConfig.getProperties();
                String sourceProjectId = properties.getString("sourceProjectId");
                String sourceEnterpriseId = properties.getString("sourceEnterpriseId");
                String sourceAppId = properties.getString("appId");
                String token = properties.getString("token");
                String roleName = properties.getString("roleName");
                if(StringUtils.isNotEmpty(sourceProjectId) && StringUtils.isNotEmpty(sourceAppId) && StringUtils.isNotEmpty(token)&& StringUtils.isNotEmpty(sourceEnterpriseId)&& StringUtils.isNotEmpty(roleName)) {
                    // 查询关联的角色信息
                    RoleQuery roleQuery = new RoleQuery();
                    List<String> nameList = new ArrayList<>();
                    if(roleName.contains(",")){
                        String[] split = roleName.split(",");
                        for(int i=0;i<split.length;i++){
                            nameList.add(split[i]);
                        }
                    }
                    else{
                        nameList.add(roleName);
                    }
                    roleQuery.setEnterpriseIdList(Arrays.asList(project.getEnterpriseId()));
                    List<Role> tmpRoleList = accountCentService.getRoleList(null, roleQuery);

                    List<Role> roleList = tmpRoleList.stream().filter(s->nameList.contains(s.getName())).collect(Collectors.toList());
                    log.info("奥莱主数据 roleList:{}",roleList);

                    if (CollectionUtils.isEmpty(roleList)) {
                        throw new BusinessException("角色数据不存在");
                    }

                    JSONObject param = new JSONObject();
                    param.put("projectId", Arrays.asList(sourceProjectId));
                    param.put("enterpriseId", sourceEnterpriseId);
                    param.put("workCodes", nameList);

                    //拉取第三方主数据列表
                    List<StaffDTO> staffList = generalAoLaiHandler.post(GET_STAFF_URL, param, configDTO.getIpAndPort(), sourceAppId, token);
                    log.error("奥莱主数据 staffList:{}",staffList.stream().map(StaffDTO::getPhone).collect(Collectors.toList()));
                    if (!CollectionUtils.isEmpty(staffList)) {
                        List<AccountDTO> exists = null;
                        try {
                            //拉取人员是否已经存在
                            AccountQuery query = new AccountQuery();
                            query.setPhoneList(staffList.stream().map(StaffDTO::getPhone).collect(Collectors.toList()));
                            exists = accountCentService.getList(query);
                        }
                        catch (Exception e){
                            log.info("奥莱主数据 通过手机或者身份证号码获取账号信息失败！");
                        }

                        List<String> phoneList = exists.stream().map(AccountDTO::getPhone).collect(Collectors.toList());
                        log.error("奥莱主数据 当前项目已存在人员 exist"+phoneList);

                        staffList.forEach(toAddStaff->{
                            if((!CollectionUtils.isEmpty(toAddStaff.getRoleNames())) && !phoneList.contains(toAddStaff.getPhone())) {
                                log.info("奥莱主数据 待添加员工角色:{}",toAddStaff.getRoleNames());
                                StaffDTO staffDTO = new StaffDTO();
                                staffDTO.setEnterpriseId(Arrays.asList(project.getEnterpriseId()));
                                staffDTO.setName(toAddStaff.getName());
                                staffDTO.setPhone(toAddStaff.getPhone());
                                staffDTO.setProjectIds(Arrays.asList(configDTO.getProjectId()));
                                staffDTO.setOrgIds(Arrays.asList(project.getOrganizationId()));
                                staffDTO.setLoginName(toAddStaff.getLoginName());
                                List<Integer> roleIdList = new ArrayList<>();
                                toAddStaff.getRoleNames().forEach(name->{
                                    Role role = roleList.stream().filter(s->StringUtils.equals(s.getName(),name)).findAny().orElse(null);
                                    if(role !=null){
                                        roleIdList.add(role.getId());
                                    }
                                });
                                if(!CollectionUtils.isEmpty(roleIdList)) {
                                    PermissionGroupDTO permissionGroupDTO = new PermissionGroupDTO();
                                    permissionGroupDTO.setProjectList(Arrays.asList(configDTO.getProjectId()));
                                    permissionGroupDTO.setRoleList(roleIdList);
                                    staffDTO.setPermissionGroupDTOs(Arrays.asList(permissionGroupDTO));
                                    staffDTO.setRoleIds(roleIdList);
                                    // 默认密码 xh+手机号码
                                    staffDTO.setPassword("xh123456");
                                    Account account = new Account();
                                    account.setIndustryId(IndustryEnum.BUZ.id);
                                    log.info("奥莱主数据 待添加员工对象:{}", staffDTO);
                                    ResultJson result = accountCentService.create(staffDTO, account);
                                    if (!result.getCode().equals(CodeEnum.SUCCESS.getCode())) {
                                        log.error("奥莱主数据 主数据绑定账号调用失败返回信息：{}", JSONObject.toJSONString(result));
                                        //throw new DataException(result.getMessage());
                                    }
                                    else{
                                        StaffDTO staffResult = MyStringUtils.jsonToObject(MyStringUtils.objectToJson(result.getResult()), StaffDTO.class);
                                        log.info("奥莱主数据 添加成功对象:{},id:{}", staffResult,staffResult.getAccountId());
                                        Account updateAccount = new Account();
                                        updateAccount.setId(staffResult.getAccountId());
                                        updateAccount.setPassword(toAddStaff.getPassword());
                                        accountCentService.updateByAccountID(updateAccount);
                                    }
                                }
                            }
                        });
                    }
                    else{
                        log.info("奥莱主数据 第三方员工数据不存在");
                    }
                }
            }
        } catch (Exception e) {
            log.error("奥莱主数据 userItcHandler:addPerson fail：{}", e.toString());
        }
        return userOpenId;
    }

    @Override
    public void afterPropertiesSet() {
        AccountFactory.register(ProductEnum.AOLAI_MAINDATA.getId(), this);
        log.info("奥莱主数据管理注册成功");
    }
}
